package top.laoshuzi.android.iotcamera.core.ui

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.SeekBar

class VerticalSeekBar : SeekBar {

    private val ROTATION_ANGLE = -90f

    private var mOnSeekBarChangeListener: SeekBar.OnSeekBarChangeListener? = null

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(h, w, oldh, oldw)
    }

    @Synchronized
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec)
        setMeasuredDimension(measuredHeight, measuredWidth)
    }

    override fun onDraw(c: Canvas) {
        // 将SeekBar转转90度
        c.rotate(ROTATION_ANGLE)
        // 将旋转后的视图移动回来
        c.translate((-height).toFloat(), 0f)
        super.onDraw(c)
    }

    override fun setOnSeekBarChangeListener(listener: SeekBar.OnSeekBarChangeListener) {
        // Do not use super for the listener, as this would not set the fromUser flag properly
        mOnSeekBarChangeListener = listener
    }

    override fun setProgress(progress: Int) {
        setProgressInternally(progress, false)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (!isEnabled) {
            return false
        }
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                setProgressInternally(max - (max * event.y / height).toInt(), true)
                mOnSeekBarChangeListener?.onStartTrackingTouch(this)
            }

            MotionEvent.ACTION_MOVE -> {
                setProgressInternally(max - (max * event.y / height).toInt(), true)
            }

            MotionEvent.ACTION_UP -> {
                setProgressInternally(max - (max * event.y / height).toInt(), true)
                mOnSeekBarChangeListener?.onStopTrackingTouch(this)
            }

            MotionEvent.ACTION_CANCEL -> {
                mOnSeekBarChangeListener?.onStopTrackingTouch(this)
            }

            else -> {
            }
        }

        return true
    }

    /**
     * Set the progress by the user. (Unfortunately, Seekbar.setProgressInternally(int, boolean) is not accessible.)
     *
     * @param progress the progress.
     * @param fromUser flag indicating if the change was done by the user.
     */
    private fun setProgressInternally(progress: Int, fromUser: Boolean) {
        if (progress != getProgress()) {
            super.setProgress(progress)
            mOnSeekBarChangeListener?.onProgressChanged(this, progress, fromUser)
        }
        onSizeChanged(width, height, 0, 0)
    }
}
